生产消费者模式
time:26_1_19
多线程开发,生成消费者模式,关键就在与三个参数。互斥。通知 和队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <iostream> #include <thread> #include <queue> #include <mutex> #include <condition_variable> #include <functional>
template <typename T> class SafeQueue { public: SafeQueue() = default;
SafeQueue(const SafeQueue&) = delete; SafeQueue& operator=(const SafeQueue&) = delete;
void enqueue(T item) { std::lock_guard<std::mutex> lock(m_mutex); m_queue.push(std::move(item)); m_cond.notify_one(); }
T dequeue() { std::unique_lock<std::mutex> lock(m_mutex); m_cond.wait(lock, [this]{ return !m_queue.empty(); }); T item = std::move(m_queue.front()); m_queue.pop(); return item; }
bool try_dequeue(T& item) { std::lock_guard<std::mutex> lock(m_mutex); if(m_queue.empty()) return false; item = std::move(m_queue.front()); m_queue.pop(); return true; }
bool empty() const { std::lock_guard<std::mutex> lock(m_mutex); return m_queue.empty(); }
private: mutable std::mutex m_mutex; std::queue<T> m_queue; std::condition_variable m_cond; };
int main() { SafeQueue<std::function<void()>> tasks;
std::thread producer([&tasks]() { for(int i = 1; i <= 5; i++) { tasks.enqueue([i]() { std::cout << "Task " << i << " executed"; }); } });
std::thread consumer([&tasks]() { for(int i = 1; i <= 5; i++) { auto task = tasks.dequeue(); task(); } });
producer.join(); consumer.join();
return 0; }
|